<template>
  <div class="container pd100">
    <div class="goods-box"
      v-if="cartList.length">
      <van-cell title="跨境商城"
        icon="shop-o">
        <div slot="default"
          class="status-tip"
          @click="onStatusClicked">{{statusTip}}</div>
      </van-cell>
      <van-checkbox-group class="list"
        v-model="checkedGoods">
        <van-checkbox class="list-item"
          v-for="(item, index) in cartList"
          :key="index"
          :name="item.id"
          checked-color="#ff4444"
          label-disabled>
          <van-card :title="item.goods.goodsName"
            :desc="item.goods.propTitle"
            :price="item.goods.sellPrice"
            :thumb="item.goods.coverImg">
            <div slot="num">
              <van-stepper v-model="item.amount"
                :min="1"
                :max="100"
                @change="onNumberChange" />
            </div>
          </van-card>

        </van-checkbox>
      </van-checkbox-group>
      <!-- 结算栏 -->
      <van-submit-bar v-if="statusTip === '管理'"
        class="submit-bar"
        :price="totalPrice | formatPoint"
        :button-text="submitBarText"
        :disabled="!checkedGoods.length"
        @submit="onSubmit">
        <van-checkbox v-model="checkedAll">全选</van-checkbox>
      </van-submit-bar>
      <!-- 删除栏 -->
      <van-submit-bar v-else
        class="delete-bar"
        button-text="删除"
        :disabled="!checkedGoods.length"
        @submit="onDeleteClicked">
        <van-checkbox v-model="checkedAll">全选</van-checkbox>
      </van-submit-bar>
    </div>
    <div class="no-data"
      v-else>
      <img src="../../assets/no-cart.png"
        alt="">
      <div class="no-data-title">购物车快饿瘪了 T.T</div>
      <div class="no-data-txt">快给我挑点宝贝</div>
      <van-button class="no-data-btn"
        plain
        type="danger"
        @click="handleHomePage">去逛逛</van-button>
    </div>
    <van-popup v-model="showPicker" round position="bottom">
        <van-picker
          title="收货地址"
          show-toolbar
          :columns="addressList"
          @confirm="onConfirm"
          @cancel="onCancel"
        />
        </van-popup>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      good: {
        id: 0,
        num: 0,
        serialNumber: 0,
        consigneeAddress: '',
        consigneePhone: '',
        consigneeName: ''
      },
      addressList: [], // 只有纯地址的列表
      addressListAll: [], // 完整地址对象数组
      showPicker: false, // 收货地址选择弹出层
      active: 0,
      statusTip: '管理', // 管理,完成
      checkedAll: false,
      checkedGoods: [], // 被选中的商品
      cartList: [] // 购物车列表

    }
  },
  computed: {
    ...mapState(['user']),
    submitBarText() {
      const count = this.checkedGoods.length
      return '结算' + (count ? `(${count})` : '')
    },
    totalPrice() {
      const price = this.cartList.reduce((total, item) => total + (this.checkedGoods.indexOf(item.id) !== -1 ? item.goods.sellPrice * item.amount : 0), 0)
      return parseFloat(price.toFixed(2))
    }
  },
  filters: {
    formatPoint(val) {
      return parseFloat((val * 100).toFixed(2))
    }
  },
  watch: {
    checkedAll() {
      this.checkedAll ? this.checkedGoods = this.cartList.map(item => item.id) : this.checkedGoods = []
    },
    checkedGoods() {
      if (this.checkedGoods.length === this.cartList.length) {
        this.checkedAll = true
      }
    }
  },
  created() {
    this.cartByUser()
    this.getAddressList()
  },
  methods: {
    /**
     * 获取收货地址
     */
    getAddressList() {
      const query = {
        userId: this.user.id
      }
      this.$api.cart.getAddressList(query).then(res => {
        if (res.code === 200) {
          this.addressListAll = res.data
          this.addressList = res.data.map(item => {
            return item.consigneeName + ' ' + item.address
          })
        }
      })
    },
    /**
     * onConfirm
     */
    onConfirm(val) {
      this.good.consigneeAddress = val.split(' ')[1]
      this.showPicker = false
      const selects = this.addressListAll.filter(item => item.address === this.good.consigneeAddress)[0]
      const selectGoods = this.cartList.filter(item => {
        return this.checkedGoods.includes(item.id)
      })
      const arr = selectGoods.map(item => {
        return {
          shoppingId: item.id,
          userId: this.user.id,
          goodsSerialNumber: item.goods.serialNumber,
          amount: item.amount,
          totalMoney: item.amount * item.goods.sellPrice,
          consigneeAddress: selects.address,
          consigneePhone: selects.consigneePhone,
          consigneeName: selects.consigneeName
        }
      })
      const params = {
        orderList: arr
      }
      this.$api.cart.epay(params).then(res => {
        if (res.code === 200) {
          // this.$router.push("/order/confirm");
          if (res.data.code) {
            this.$router.push({
              path: '/order-detail',
              query: {
                id: res.data.code
              }
            })
          }
        }
      })
      // this.$router.push({ path: '/order-submit', query: { type: 'cart', checkedGoods: this.checkedGoods }})
    },
    /**
     * onCancel
     */
    onCancel() {
      this.showPicker = false
    },
    /**
     * 获取购物车商品列表
     */
    cartByUser() {
      const query = {
        userId: this.user.id
      }
      this.$api.cart.cartByUser(query).then(res => {
        if (res.code === 200) {
          this.cartList = res.data
        }
      })
    },
    /**
     * 到首页
     */
    handleHomePage() {
      this.$router.replace({ path: '/home' })
    },
    /**
     * 状态管理
     */
    onStatusClicked() {
      this.statusTip === '管理' ? this.statusTip = '完成' : this.statusTip = '管理'
    },
    /**
     * 删除商品
     */
    onDeleteClicked() {
      this.$dialog.confirm({
        message: `确定要删除这${this.checkedGoods.length}个商品吗?`
      }).then(() => {
        this.checkedGoods.forEach((item, index) => {
          const params = {
            id: item
          }
          this.$api.cart.delCart(params).then(res => {
          })
        })
        this.cartList = this.cartList.filter(item => !(this.checkedGoods.indexOf(item.id) !== -1))
        this.checkedGoods = []
      })
    },
    /**
     * 数量改变
     */
    onNumberChange(val) {
    },
    /**
     * 购物车支付
     */
    onSubmit() {
      if (this.addressListAll.length === 0) {
        this.$toast.fail('还没有收货地址哦~')
        return
      } else {
        this.showPicker = true
      }
    }
  }
}
</script>
<style lang="less" scoped>
.status-tip {
  position: relative;
  overflow: hidden;
  color: #38f;
  text-align: right;
  vertical-align: middle;
}
.list {
  padding: 10px 0;
  background-color: #fff;
  &-item {
    position: relative;
    .van-card {
      background-color: #fff;
    }
    /deep/ .van-checkbox__label {
      width: 100%;
      height: auto; // temp
      padding: 0 10px 0 15px;
      box-sizing: border-box;
    }
    /deep/ .van-checkbox__icon {
      top: 50%;
      left: 10px;
      z-index: 1;
      position: absolute;
      margin-top: -10px;
      font-size: 16px;
    }
    .van-card__price {
      color: #f44;
    }
    .van-card__bottom {
      display: flex;
      align-items: flex-end;
      justify-content: space-between;
    }
  }
}
.delete-bar {
  .van-submit-bar__bar {
    margin-left: 10px;
    justify-content: space-between;
    align-items: center;
  }
  /deep/.van-checkbox__icon--checked .van-icon {
    background-color: #f44;
    border-color: #f44;
  }
}
.submit-bar {
  bottom: 50px;
  .van-checkbox {
    margin-left: 10px;
  }
  /deep/.van-checkbox__icon--checked .van-icon {
    background-color: #f44;
    border-color: #f44;
  }
}
.no-data {
  padding-top: 150px;
  text-align: center;
  > img {
    display: inline-block;
    width: 290px;
    margin-bottom: 20px;
  }
  &-title {
    font-size: 16px;
    color: #666;
    font-weight: 400;
    margin-bottom: 10px;
  }
  &-txt {
    font-size: 14px;
    color: #999;
    margin-bottom: 10px;
  }
  &-btn {
    padding: 0 20px;
    height: 34px;
    line-height: 32px;
  }
}
</style>

